import { Inject, Controller, Post, Body,Get } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { Validate } from '@midwayjs/validate';
import { ErrCode } from '../common/ErrCode';
import { Tools } from '../common/Tools';
import { NetWorkBaseData } from '../dto/base.dto';
import { JoinPartnerDTO, JoinPartnerGroup, QueryPartnerDTO } from '../dto/partner.dto';
import { UserBindDTO, UserLoginDTO, UserOaCodeDTO, UserPhoneCodeDTO, UserPhoneVerCodeDTO, UserRechargeDTO, UserWechatLoginDTO } from '../dto/user.dto';
import { CurrencyLog } from '../entity/CurrencyLog.entity';
import { partnerGroupBuy } from '../entity/partnerGroupBuy.entity';
import { PartnerInfo } from '../entity/partnerInfo.entity';
import { PartnerType } from '../entity/partnerType.entity';
import { UserPartner } from '../entity/userPartner.entity';
import { INetWorkBase, IPagingData, IReturnData } from '../interfaces/IBase.interface';
import { UserAddendType } from '../interfaces/IPartner.interface';
import { WechatLoginType } from '../interfaces/IUser.interface';
import { IJsapiClientPay, IWechatErrResult } from '../interfaces/IWechat.interface';
import { UserMiddleware } from '../middleware/user.middleware';
import { PartnerService } from '../service/partner.service';
import { PayService } from '../service/pay.service';
import { SMSServices } from '../service/SMS.service';
// import { PayService } from '../service/pay.service';
import { UserService } from '../service/user.service';
import { WechatService } from '../service/wechat.service';

@Controller('/api',{ middleware: [ UserMiddleware] })
export class APIController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @Inject()
  partnerService:PartnerService;

  @Inject()
  smsService:SMSServices;

  @Inject()
  wechatService:WechatService;

  @Inject()
  payService:PayService;

  @Get('/test')
  async test(@Body() data:INetWorkBase<UserWechatLoginDTO>):Promise<IReturnData<any>> {
    // const user = await this.userService.getUser({ uid });
    // return { success: true, message: 'OK', data: user };
    // let result = await this.userService.wechatLogin({code:data.data.code,type:WechatLoginType.Small});
    // console.log(result)
    console.log(Tools.timestamp);
    return {code:ErrCode.SYSTEM_SUCCESS,data:Tools.md5(Tools.instance.Random(1,1000000))}
  }
  @Post('/reg')
  @Validate()
  async registered(@Body() reg:UserLoginDTO):Promise<IReturnData<any>>{
      const code:ErrCode = await this.userService.registered(reg);
      return {code:code}
  }
  // @Post('/login')
  // @Validate()
  // async login(@Body() logininfo:UserLoginDTO ):Promise<IReturnData<any>>{
  //     const result:ErrCode|UserInfo = await this.userService.login(logininfo);
  //     if(result == ErrCode.USER_LGIN_FAIL_PWD || result == ErrCode.USER_NOT_FOUND){
  //       return {code:result}
  //     }else{
  //       return {code:ErrCode.USER_LOGIN_SUCCESS,data:result}//this.ReturnData(ErrCode.USER_LOGIN_SUCCESS,code);
  //     }
  // }

  @Post('/login')
  @Validate()
  async loginWeChat(@Body() data:UserWechatLoginDTO):Promise<IReturnData<any>>{
      let result:any = await this.userService.wechatLogin({code:data.code,type:data.type});
      if(typeof(result) == 'number'){
        return {code:result};
      }
      if(result.errcode != null && result.errmsg != null){
            return {code:result.errcode,message:result.errmsg}
      }
      return {code:ErrCode.SYSTEM_SUCCESS,data:result};
  }

  @Post('/getOACode')
  @Validate()
  async getOACode(@Body() data:UserOaCodeDTO):Promise<IReturnData<any>>{
        let result:string|ErrCode = await this.wechatService.OAgetCodeUrl(data.url,data.scope == null?"snsapi_base":data.scope);
        if(typeof(result) == 'string'){
            return {code:ErrCode.SYSTEM_SUCCESS,data:result}
        }
        return {code:result};
  }

  @Post('/userInfo')
  @Validate()
  async getUser(@Body() data:NetWorkBaseData<UserWechatLoginDTO>):Promise<IReturnData<any>>{
      let result = await this.userService.wechatLogin({code:data.data.code,type:WechatLoginType.Small});
      return {code:ErrCode.SYSTEM_SUCCESS,data:result};
  }

  @Post('/bind')
  @Validate()
  async BindUserInfo(@Body() data:NetWorkBaseData<UserBindDTO>):Promise<IReturnData<any>>{
        let result:ErrCode = await this.userService.BindUserInfo(data.userid,data.data);
        return {code:result};
  }
  @Post('/getCode')
  @Validate()
  async getPhoneCode(@Body() data:NetWorkBaseData<UserPhoneCodeDTO>):Promise<IReturnData<any>>{
        let codes = await this.smsService.getPhoneCode(data.data.phone);
        return {code:codes}
  }
  @Post('/verCode')
  @Validate()
  async verPhoneCode(@Body() data:NetWorkBaseData<UserPhoneVerCodeDTO>):Promise<IReturnData<any>>{
        let codes = await this.smsService.checkPhoneCode(data.data.phone,data.data.code);
        return {code:codes}
  }

  @Post('/checkEquities')
  @Validate()
  async CheckUserEquities(@Body() data:NetWorkBaseData<any>):Promise<IReturnData<any>>{
        let result = await this.userService.CheckUserEquities(data.userid);
        if(result == ErrCode.SYSTEM_FAIL){
            return {code:result};
        }
        return {code:result};
  }

  @Post('/partnerType')
  @Validate()
  async GetPartnerTypeList():Promise<IReturnData<any>>{
        let list:PartnerType[] = await this.partnerService.GetPartnerTypeList();
        return {code:ErrCode.SYSTEM_SUCCESS,data:list}
  }

  @Post('/joinPartner')
  @Validate()
  async JoinPartner(@Body() data:NetWorkBaseData<JoinPartnerDTO>):Promise<IReturnData<any>>{
      let result = await this.partnerService.joinPartner(data.userid,data.data.serialNo,0,UserAddendType.JoinGroup);
      return {code:ErrCode.SYSTEM_SUCCESS,data:result};
  }

  @Post('/userPartner')
  @Validate()
  async getUserPartner(@Body() data:NetWorkBaseData<IPagingData>):Promise<IReturnData<any>>{
      let list:UserPartner[] = await this.partnerService.getUserPartner(data.userid,data.data);
      return {code:ErrCode.SYSTEM_SUCCESS,data:list};
  }

  @Post('/partnerlist')
  @Validate()
  async getPartnerList(@Body() data:NetWorkBaseData<IPagingData>):Promise<IReturnData<any>>{
      let list:PartnerInfo[] = await this.partnerService.getPartnerList(data.data);
      list.map((item)=>{
        if(item.detailsImage != null){
            item.detailsImage = JSON.parse(item.detailsImage);
        }
        if(item.thumbnailImage != null){
            item.thumbnailImage = JSON.parse(item.thumbnailImage);
        }
      })
      return {code:ErrCode.SYSTEM_SUCCESS,data:list};
  }

  @Post('/queryPartner')
  @Validate()
  async getPartnerByid(@Body() data:NetWorkBaseData<QueryPartnerDTO>):Promise<IReturnData<any>>{
      let info:PartnerInfo = await this.partnerService.getPartnerById(data.data);
      return {code:ErrCode.SYSTEM_SUCCESS,data:info};
  }

  @Post('/openGroup')
  @Validate()
  async openGroup(@Body() data:NetWorkBaseData<QueryPartnerDTO>):Promise<IReturnData<any>>{
      let info:ErrCode|IJsapiClientPay|IWechatErrResult = await this.partnerService.openGroup(data.userid,data.data.partnerid);
      if(typeof(info) == 'number'){
        return {code:info};
      }
      if((info as IJsapiClientPay).appId != null){
        return {code:ErrCode.USER_LACK_BALANCE,data:info};
      }
      return {code:ErrCode.SYSTEM_SUCCESS,data:info};
  }
  
  @Post('/joinGroupbyid')
  @Validate()
  async joinGroupbyid(@Body() data:NetWorkBaseData<JoinPartnerGroup>):Promise<IReturnData<any>>{
      let info:ErrCode|IJsapiClientPay|IWechatErrResult = await this.partnerService.joinGroupByid(data.userid,data.data.groupid);
      if(typeof(info) == 'number'){
        return {code:info};
      }
      if((info as IJsapiClientPay).appId != null){
        return {code:ErrCode.USER_LACK_BALANCE,data:info};
      }
      return {code:ErrCode.SYSTEM_SUCCESS,data:info};
  }
  @Post('/joinGroup')
  @Validate()
  async joinGroup(@Body() data:NetWorkBaseData<QueryPartnerDTO>):Promise<IReturnData<any>>{
      let info:ErrCode|IJsapiClientPay|IWechatErrResult = await this.partnerService.joinGroup(data.userid,data.data.partnerid);
      if(typeof(info) == 'number'){
        return {code:info};
      }
      if((info as IJsapiClientPay).appId != null){
        return {code:ErrCode.USER_LACK_BALANCE,data:info};
      }
      return {code:ErrCode.SYSTEM_SUCCESS,data:info};
  }

  @Post('/grouplist')
  @Validate()
  async grouplist(@Body() data:NetWorkBaseData<QueryPartnerDTO>):Promise<IReturnData<any>>{
      let list:partnerGroupBuy[] = await this.partnerService.getGroupByPartnerid(data.data.partnerid);
      list.map((item)=>{
        let filter = ['clustersNum','currentNum','endtime'];
        for(let key in item){
            if(filter.indexOf(key) == -1){
                delete item[key];
            }
        }
      });
      return {code:ErrCode.SYSTEM_SUCCESS,data:list};
  }

  @Post('/currencyDetail')
  @Validate()
  async currencyDetail(@Body() data:NetWorkBaseData<IPagingData>):Promise<IReturnData<any>>{
      let list:CurrencyLog[] = await this.userService.getCurrenyList(data.userid,data.data);
      return {code:ErrCode.SYSTEM_SUCCESS,data:list};
  }

  @Post('/recharge')
  @Validate()
  async recharge(@Body() data:NetWorkBaseData<UserRechargeDTO>):Promise<IReturnData<any>>{
        let result:IJsapiClientPay|IWechatErrResult|ErrCode = await this.payService.Recharge(data.userid,data.data.price);
        if(typeof(result as ErrCode) == 'number'){
            return {code:result as ErrCode};
        }
        if((result as IWechatErrResult).message != null){
            return {code:ErrCode.SYSTEM_FAIL,message:(result as IWechatErrResult).message};
        }
        return {code:ErrCode.SYSTEM_SUCCESS,data:result};
  }

  @Post('/RechargeDiscountsList')
  @Validate()
  async RechargeDiscountsList(@Body() data:NetWorkBaseData<any>):Promise<IReturnData<any>>{
        let list = await this.payService.getRechargeDiscountsList();
        if(typeof(list as ErrCode) == 'number'){
            return {code:list};
        }
        return {code:ErrCode.SYSTEM_SUCCESS,data:list};
  }
}
